/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: BehaviourServer.cpp,v 1.7 2009-06-17 10:09:54 morsko Exp $
 *
 * \file
 * \brief Implementation of Behaviour interface Server.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 */

#include "BehaviourServer.hpp"
#include "binbag.h"

//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
using namespace MaCI::Behaviour;
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

CBehaviourServer::CBehaviourServer(MaCICtrl::CMaCICtrlServer *aMaCICtrlServerPtr, 
                                 const int aInterfaceMinor,
                                 const std::string &aDescription)
  : CMaCI(aMaCICtrlServerPtr, GIMI_PROTOCOL_MACI_BEHAVIOUR, aInterfaceMinor),
    CThread(1),
    CSync(1,1),
    iServerActive(false),
    iBehaviourTypeSet(false),
    iServiceDescription(aDescription),
    iBehaviourData(),
    iBehaviourType()
{
}
//*****************************************************************************

CBehaviourServer::~CBehaviourServer()
{
  DoClose();
}
//*****************************************************************************
   
MaCI::EMaCIError CBehaviourServer::DoOpen(void)
{
  EMaCIError result = KMaCIError;
  assert(this != NULL);
  assert(iGIMIPtr != NULL);
  
  // Execute only if server is not active.
  if (!iServerActive && iBehaviourTypeSet) {
    // Register service.
    RegisterProvidedService("MaCI-BehaviourServer-BehaviourControl; '" + iServiceDescription + "'");
    RegisterAcceptedService("MaCI-BehaviourServer-Cmd; '" + iServiceDescription + "'");

    // Start the handler Thread
    iServerActive = true;
    CThread::RunThread();
    result = KMaCIOK;
    
    dPrint(4,"Succesfully Open():ed BehaviourServer instance %p.", this);
  }else{
    if(iServerActive){
      dPrint(3,"Server already active");
    }
    if(!iBehaviourTypeSet){
      dPrint(3,"Behaviour type hasn't been set! Can't open the Server");
    }
  }
    
  return result;
}
//*****************************************************************************

MaCI::EMaCIError CBehaviourServer::DoClose(void)
{
  EMaCIError result = KMaCIError;
  assert(this != NULL);
  assert(iGIMIPtr != NULL);

  // Execute block only if server is currently active.
  if (iServerActive) {
    // Unregister services
    UnregisterProvidedService();
    UnregisterAcceptedService();
    
    // Stop the handler Thread
    iServerActive = false;
    /* CThread::CancelThread(); //Removed by script */
    CThread::WaitThread();

    dPrint(4,"Succesfully Close():ed BehaviourServer instance %p", this);
  }
  
  return result;
}
//*****************************************************************************

bool CBehaviourServer::SendBehaviourControlEvent(const CBehaviourData &aData)
{
  bool result = false;

  assert(iGIMIPtr != NULL);
  const TBehaviourControl *bc = aData.GetBehaviourControl();
  if(bc){
   
     EMaCIError e = 
       SendInterfaceSubscriberMessage(aData.GetBinBagContainerPtr()->GetBuffer(),
                                      aData.GetBinBagContainerPtr()->GetBufferSize());
    result = (e == KMaCIOK);

  } else {
    const TBehaviourControlSpeed *bcS= aData.GetBehaviourControlSpeed();
    if(bcS){
      EMaCIError e = 
        SendInterfaceSubscriberMessage(aData.GetBinBagContainerPtr()->GetBuffer(),
                                       aData.GetBinBagContainerPtr()->GetBufferSize());
      result = (e == KMaCIOK);

      
    } else {
      dPrint(4,"No TBehaviourControl element in container, will not send!");
    }
  }

  return result;
}
//*****************************************************************************
 
bool CBehaviourServer::SendBehaviourStateEvent(bool aState){
  bool result = false;
  gim::binbag::CBinBag bb;
  CBehaviourData data;
  data.EncodeTo(&bb);
  data.SetCommand(TCommand(KCommandBehaviourStateEvent));
  if(aState){
    data.SetBehaviourState(TBehaviourState(1));
  }else{
    data.SetBehaviourState(TBehaviourState(0));
  }

  EMaCIError e = 
    SendInterfaceSubscriberMessage(data.GetBinBagContainerPtr()->GetBuffer(),
                                   data.GetBinBagContainerPtr()->GetBufferSize());
  result = (e == KMaCIOK);

  return result;
}   
//*****************************************************************************

void CBehaviourServer::SetBehaviourType(EBehaviourType aType)
{

  iBehaviourType = aType;
  iBehaviourTypeSet = true;

}
//*****************************************************************************

MaCI::EMaCIError CBehaviourServer::WaitCommand(CBehaviourData &aData, 
                                               const unsigned int aTimeout_ms)
{
  EMaCIError result = KMaCIError;
  const unsigned int time_begin = ownTime_get_ms();
  int timeout = aTimeout_ms;

  aData.Reset();
  Lock();
  do {
    //Wait for notification of new data
    Wait(timeout);
    timeout = aTimeout_ms - ownTime_get_ms_since(time_begin);
  
    if(timeout > 0){
      //Copy the data and stop the loop
      aData = iBehaviourData;
      result = KMaCIOK;
      break;
    }else{
      dPrint(8,"No command within timeout (Timeout %dms)",
	       aTimeout_ms);
    }
  } while(timeout > 0 && iServerActive);
  Unlock();

  // Change result type if timeout was the reason.
  if (timeout <= 0) result = KMaCITimeout;


  return result;
}
//*****************************************************************************
int CBehaviourServer::ThreadFunction(const int aThreadNumber)
{
  int result = 0;
  EMaCIError e;
  gimi::GIMIMessage gmsg;
  
  assert(aThreadNumber == 0);
  assert(iGIMIPtr != NULL);
  
  dPrint(4, "GIMIMessage handler started");
  
  // Run as long as the thread should be active
  while(iServerActive) {
    dPrint(10,"Server thread running");
    // Call the ReceiveMessage wrapper with 1s timeout
    e = ReceiveInterfaceMessage(gmsg, 1000);
    if (e == KMaCIOK) {
      dPrint(10,"Got GIMIMessage %d - Processing.", gmsg.messageId);
      ProcessMessage(gmsg);
      
    } else if (e != KMaCITimeout) {
      // Other error, try to recover by sleeping one second.
      ownSleep_ms(1000);
      
    }
  }
  
  dPrint(4, "GIMIMessage handler stopped");

  return result;
}
//*****************************************************************************

int CBehaviourServer::ProcessMessage(const gimi::GIMIMessage &msg)
{
  int result = 0;
  gim::binbag::CBinBag bb;
  CBehaviourData d;
  bool r;

  r = bb.Decode(msg.getData(), msg.getDatalength());
  if (r) {
    // Succesfully decoded as BinBag.
    r = d.DecodeFrom(&bb);
    if (r) {

      // Succesfully decoded as BehaviourData
      // Now, Check whether it was Command, if so, process it and construct reply
      gim::binbag::CBinBag replybb;
      CBehaviourData reply;
      bool send_reply = false;

      // Do encoding to this binbag
      reply.EncodeTo(&replybb);
      
      const TCommand *cmd = d.GetCommand();
      if (cmd) {
        switch(cmd->cmd) {
          
          // Set Commands: by default passed to user
        case KCommandStart:
        case KCommandStop: 
        case KCommandGetBehaviourStateEvent:{
          // Default action for Set commands is to save them to CommandQueue
          
          // Debug
          dPrint(8, "Got Command to be passed to User (Command was %d)",
                 cmd->cmd);
          
          // Save the data
          Lock();
          iBehaviourData = CBehaviourData(d);

          Notify();
          Unlock();
          break;
        }
        case KCommandGetInfo:{
          //Setting behaviourInfo, and sending reply
          dPrint(8,"Asked for behaviour info.")
          reply.EncodeTo(&replybb);
          reply.SetCommand(TCommand(KCommandGetInfoReply));
          reply.SetBehaviourInfo(TBehaviourInformation(iBehaviourType));
          send_reply = true;

        }
         
        default:
          if(cmd->cmd != KCommandGetInfo){
            dPrint(4,"Unidentified command! %d (%x)! Ignore.",
                   cmd->cmd, cmd->cmd);
          }
          break;
        }
      }
      
      // Check whether reply needs to be sent
      if (send_reply) {

	int gr = iGIMIPtr->send(msg.getSenderId(),
				replybb.GetBuffer(),
				replybb.GetBufferSize(),
				iInterfaceMajor,
				iInterfaceMinor,
				msg.messageId); // Reply with same ID
	if (gr == GIMI_OK) {
	  dPrint(8,"Succesfully sent message with %d BinBag elements to '%p'",
		 replybb.GetElementCount(),
		 msg.getSenderId());

	} else {
	  
	  dPrint(8,"Failed to send message with %d BinBag elements to '%p'",
		 replybb.GetElementCount(),
		 msg.getSenderId());
	}
      }
    }else{
      dPrint(3,"DecodeFrom FAILED!");
    }
  }
  
  return result;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

 
